var Models = require('../db/db.js');
var express = require('express');
var router = express.Router();


router.use((req, res, next) => {
	console.log('触发api');
	next();
});

router.get('/', function(req, res, next) {
  res.json({ message: 'welcome to our api!!' });
});

router.get('/getAllUser',(req, res, next) => {
	console.log('获取全部的用户列表');
	Models.UserSchema.find({})
			.exec((err, result) => {
		      if (err) {
		        console.log(err);
		      } else {
		      	console.log(result)
		        res.send(result);
		      }
		    })
});

router.post('/addUser', (req, res, next) => {
  let newItem = req.body.newItem;
  console.log(newItem);
  Models.UserSchema.create(newItem, (err) => {
    if (err) {
      console.log('发生错误');
      console.log(err);
    } else {
      console.log('添加成功');
      Models.UserSchema.find({}, (err,result) => {
        if(err){
          console.log(err);
        }else{
        	console.log(result)
          	res.json(result);
        }
      });
    }
  })
})

module.exports = router;